const fs   = require('fs');
const util = require('util');
const path = require('path');
const http = require('http');
const exec = require('child_process').exec;

const host = 'tencent.beecdn.cn';

const resources = {
    'hammer.js' : [
        '2.0.8'
    ]
};

const uri = '/%s/files/%s';

const CheckFolder = function( dest ){
    if( !fs.existsSync(dest) )
        fs.mkdirSync(dest);
    else{
        let stat = fs.statSync(dest);
        if( !stat.isDirectory() ){
            fs.unlinkSync(dest);
            fs.mkdirSync(dest);
        }
    }
};

const CheckVersionDetails = function( uri , callback ){
    let req = http.request({
        host: 'cdn.open.beeapi.cn',
        path: uri,
        method: 'GET'
    }, (response) =>{
        response.setEncoding('utf8');
        let body = '';
        response.on('data', (chunk) => {
            body += chunk;
        });
        response.on('end', () => {
            body = JSON.parse(body);
            if( body.code === 1 && typeof callback === 'function' )
                callback(body.data);
        });
    });

    req.end();
};

var Count = 0;
var Over  = 0;
var isRunning = false;
const cmds = [];
const DownloadQueue = function(){
    if( cmds.length > 0 && !isRunning ){
        isRunning = true;
        let item = cmds.shift();
        let req = http.request({
            host: host,
            path: item.uri,
            method: 'GET'
        }, (response) =>{
            let body = '';
            response.on('data', (chunk) => {
                body += chunk;
            });
            response.on('end', () => {
                fs.writeFileSync(item.path, body);
                ++Over;

                console.log(util.format('over %d/%s', Over, Count));

                setTimeout(function(){
                    isRunning = false;
                    DownloadQueue();
                }, 200);
            });
        });

        req.end();
    }
};

const Download = function( src , dest ){
    let uri = util.format('/libs/%s', src);
    ++Count;

    cmds.push({
        uri: uri,
        path: path.resolve('./', dest)
    });

    DownloadQueue();
};

const DownloadResource = function( folder , name , version , file ){
    let dirs = file.split('/');
    let last = dirs.length - 1;

    dirs.forEach((dir, index) => {
        folder = path.join(folder, dir);

        if( last === index ){
            if( fs.existsSync(folder) ){
                let stat = fs.statSync(folder);
                if( !stat.isFile() ){
                    fs.unlinkSync(folder);
                    Download(util.format('%s/%s/%s', name, version, file), folder);
                } else if( stat.isFile() && stat.size < 1 )
                    Download(util.format('%s/%s/%s', name, version, file), folder);
            }
            else
                Download(util.format('%s/%s/%s', name, version, file), folder);
        }
        else
            CheckFolder(folder);
    });
};

for(let name in resources){
    let folder = path.join('./libs', name);
    CheckFolder(folder);

    let versions = resources[name];
    versions.forEach(version => {
        let versionFolder = path.join(folder, version);
        CheckFolder(versionFolder);
        CheckVersionDetails(util.format(uri, name, version), (files) => {
            for(let file of files)
                DownloadResource(versionFolder, name, version, file);
        });
    });
}

while(Over < Count);